package utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapIterator;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.web.servlet.ModelAndView;



public class Utils {
	
	public static void makeDir(String path ) {
		try { 
			org.apache.commons.io.FileUtils.forceMkdir(new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void makeDir(File f ) {
		try {
			org.apache.commons.io.FileUtils.forceMkdir(f);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void deleteOldFiles(String saveDir ){
	    Iterator it = FileUtils.iterateFiles(new File(saveDir), null, false);
	    String strFilename;
	    while (it.hasNext()){
	        strFilename = it.next().toString();
	        boolean isOld = FileUtils.isFileOlder(new File(strFilename),System.currentTimeMillis()-3600000);
	        if(isOld){
	        	try {
					FileUtils.forceDelete(new File(strFilename));
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
	    }
	}
	
	public static String writeXML(List list) {
		StringBuffer sb = new StringBuffer();
	
		sb.append("<rows>\r\n");
		Map  map;
		for(int i=0;i<list.size();i++){
			map = (Map)list.get(i);
			MapIterator mapit = new HashedMap(map).mapIterator();
			
			sb.append("<record>\r\n");
			try{
				while (mapit.hasNext()) {
					String key = mapit.next().toString();
					String value = "";
					if(mapit.getValue()!=null){
						value = mapit.getValue().toString();
					}
	
					sb.append("<"+key.toLowerCase()+">");
					sb.append(StringEscapeUtils.escapeXml(value));
					sb.append("</"+key.toLowerCase()+">");
				}
			}catch(Exception e){}
			sb.append("</record>\r\n");
		}
		sb.append("</rows>\r\n");
		
	    return sb.toString();
	}
	
	public static int getErrcode(List list) {
		String value = "";
		Map  map;
		for(int i=0;i<list.size();i++){
			map = (Map)list.get(i);
			MapIterator mapit = new HashedMap(map).mapIterator();
			try{
				while (mapit.hasNext()) {
					String key = mapit.next().toString();

					if(key.equals("msgcode")){
						if(mapit.getValue()!=null){
							value = mapit.getValue().toString();
						}
					}
				}
			}catch(Exception e){}
		}
	    return new Integer(value);
	}

	public static int getIntReturnKey(List list, String inKey) {
		String value = "0";
		Map  map;
		for(int i=0;i<list.size();i++){
			map = (Map)list.get(i);
			MapIterator mapit = new HashedMap(map).mapIterator();
			try{
				while (mapit.hasNext()) {
					String key = mapit.next().toString();
					if(key.equals(inKey)){
						if(mapit.getValue()!=null){
							value = mapit.getValue().toString();
						}
					}
				}
			}catch(Exception e){}
		}
	    return new Integer(value);
	}

	public static String getStrReturnKey(List list, String inKey) {
		String value = "";
		Map  map;
		for(int i=0;i<list.size();i++){
			map = (Map)list.get(i);
			MapIterator mapit = new HashedMap(map).mapIterator();
			try{
				while (mapit.hasNext()) {
					String key = mapit.next().toString();
					if(key.equals(inKey)){
						if(mapit.getValue()!=null){
							value = mapit.getValue().toString();
						}
					}
				}
			}catch(Exception e){}
		}
	    return new String(value);
	}	
	
	public static ModelAndView errorHandler(HttpServletRequest request, String errMsg, String errCode) {
		
		ModelAndView mav = new ModelAndView("");				
		mav.setViewName("/shop/common/Error");
		mav.addObject("errCode",errCode);
		mav.addObject("errMsg",errMsg.replace("\n", "<br>"));
		return mav;
	}

	public static String convertHtmlcharsIn(String htmlstr)
	{
		String convert = new String();
		convert = replace2(htmlstr, "<script>", "");
		convert = replace2(convert, "</script>", "");
		//convert = replace2(convert, "<p>", "");
		//convert = replace2(convert, "</p>", "");
		//convert = replace2(convert, "&nbsp;", " ");
		//convert = replace2(convert, "<", "&lt;");
		//convert = replace2(convert, ">", "&gt;");
		//convert = replace2(convert, "\"", "&quot;");
		//convert = replace2(convert, "&nbsp;", "&amp;nbsp;");
		return convert;
	}

	public static String convertHtmlcharsOut(String htmlstr)
	{
		String convert = new String();
		convert = replace2(htmlstr, "&lt;", "<");
		convert = replace2(convert, "&gt;", ">");
		convert = replace2(convert, "&quot;", "\"");
		convert = replace2(convert, "&amp;nbsp;", "&nbsp;");
		return convert;
	}

	public static String replace2(String original, String oldstr, String newstr)
	{
		String convert = new String();
		int pos = 0;
		int begin = 0;
		pos = original.indexOf(oldstr);

		if(pos == -1)
			return original;

		while(pos != -1)
		{
			convert = convert + original.substring(begin, pos) + newstr;
			begin = pos + oldstr.length();
			pos = original.indexOf(oldstr, begin);
		}
		convert = convert + original.substring(begin);

		return convert;
	}
	
	
	/**
	 *  <br> 태그로 변환 
	 * Auth : yumi
	 * Date : 2011. 07. 29
	 * @param 
	 * @param 
	 * @return  String
	 * @TODO : TODO
	 */
	public static String br(String content){
	    if (content == null)
	      return "";
	    return content.replaceAll("\n", "<br/>");
	}
	
	public static String nullToString(String str)
	{		
		if(str == null)
		{
			str = "";
		}			
		else
		{				
			str = str;
		}		
		return str;
	}
	
	
	
	/**
	 * 게시물 제목 size만큼 자르기
	 * Auth : Lucy
	 * Date : 2011. 08. 04
	 * @param 
	 * @param 
	 * @return  String
	 * @TODO : TODO
	 */
	public static String TitleCut(String Title, int size ){
		String Titl="";
		if(Title.length()>size ){
			Titl=Title.substring(0,size)+"...";
			}
		else{
			Titl=Title;
			}
		
		return Titl;
		
	}
	
	/**
	 * 날짜반환(현재시간) 메소드
	 * Auth : Lucy
	 * Date : 2011. 08. 04
	 * @param 
	 * @param 
	 * @return  String
	 * @TODO : TODO
	 */
	public static String getDateString(){
		
		Calendar cal = Calendar.getInstance();
		String year = Integer.toString(cal.get(Calendar.YEAR));
		//오늘날짜의 해당 월을 구함. 1월은 0이기 때문에 + 1
		String month = Integer.toString((cal.get(Calendar.MONTH) + 1));
		//한자리 숫자, 예를 들면 1월인 경우 "01"등으로 문자열 변환
		month = month.length() > 1 ? month : "0" + month;
		//오늘의 날짜 구함
		String day = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
		day = day.length() > 1 ? day : "0" + day;
		//현재 시각의 시를 구함.
		String hh = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
		//현재 시각의 분을 구함.
		String mm = Integer.toString(cal.get(Calendar.MINUTE));
		//오늘의 요일을 구함
		String WeekDay = Integer.toString(cal.get(Calendar.DAY_OF_WEEK));
		//오늘이 1~5번째 주중 몇번째 주인지 구함. 
		String WeekOfMonth = Integer.toString(cal.get(Calendar.WEEK_OF_MONTH));
		//오늘을 기준으로 3주전 날짜로 수정
		//cal.add(Calendar.WEEK_OF_MONTH, -3);
		
		return year+month+day+hh+mm;
		
	}
	
	
}
